package com.sunwayworld.basemodule.business.ordertask.io;

import com.sunwayworld.basemodule.basedata.exporttemplate.service.LimsGenericTemplateService;
import com.sunwayworld.basemodule.business.ordertask.bean.LimsRunBoardHoleBean;
import com.sunwayworld.basemodule.business.ordertask.service.LimsRunBoardHoleService;
import com.sunwayworld.basemodule.business.result.bean.LimsRunBean;
import com.sunwayworld.basemodule.business.result.service.LimsRunService;
import com.sunwayworld.framework.i18n.I18nHelper;
import com.sunwayworld.framework.io.excel.utils.ExcelUtils;
import com.sunwayworld.framework.mybatis.mapper.MatchPattern;
import com.sunwayworld.framework.mybatis.mapper.SearchFilter;
import com.sunwayworld.framework.spring.annotation.GikamBean;
import com.sunwayworld.framework.utils.StringUtils;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Path;
import java.util.List;

@Component(value = "LimsRunBoardHoleExportTemplate")
@GikamBean
public class LimsRunBoardHoleExportTemplate implements LimsGenericTemplateService<String> {

    @Autowired
    private LimsRunBoardHoleService limsRunBoardHoleService;

    @Autowired
    private LimsRunService limsRunService;

    @Override
    public void initTemplateData(Path path, String id) {
        if (StringUtils.isEmpty(id)) {
            return;
        }
        List<LimsRunBoardHoleBean> runBoardHoleBeans = limsRunBoardHoleService.selectListByFilter(SearchFilter.instance()
                .match("boardId", id).filter(MatchPattern.EQ));
        LimsRunBean runBean = limsRunService.selectByIdIfPresent(Long.parseLong(id));
        try {
            InputStream in = new FileInputStream(path.toString());
            Workbook workBook = WorkbookFactory.create(in);
            Sheet sheet = workBook.getSheetAt(0);

            if (!runBoardHoleBeans.isEmpty()) {
                addInfo(sheet, workBook, runBean, runBoardHoleBeans);
            }

            in.close();
            FileOutputStream outputStream = new FileOutputStream(path.toString());
            workBook.write(outputStream);
            outputStream.close();
            workBook.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }


    private void addInfo(Sheet sheet, Workbook wb, LimsRunBean runBean, List<LimsRunBoardHoleBean> runBoardHoleBeans) {
        CellStyle leftCellStyle = ExcelUtils.getLeftCellStyle(wb);
        leftCellStyle.setBorderTop(BorderStyle.THIN);

        CellStyle centerCellStyle = ExcelUtils.getCenterCellStyle(wb);
        centerCellStyle.setBorderTop(BorderStyle.THIN);
        centerCellStyle.setBorderBottom(BorderStyle.THIN);

        int fromRowNum = 1;
        int fromColNum = 1;
        int x = runBoardHoleBeans.stream().map(LimsRunBoardHoleBean::getX).max(Integer::compareTo).get();
        int y = runBoardHoleBeans.stream().map(LimsRunBoardHoleBean::getY).max(Integer::compareTo).get();

        Row runCodeRow = sheet.createRow(fromRowNum);
        Cell runCodeCell = runCodeRow.createCell(fromColNum);
        runCodeCell.setCellStyle(leftCellStyle);
        runCodeCell.setCellValue(I18nHelper.getMessage("T_LIMS_RUN.RUNCODE").concat("：").concat(runBean.getRunCode()));
        for (int i = 1 + fromColNum; i <= x + fromColNum; i++) {
            Cell cell = runCodeRow.createCell(i);
            cell.setCellStyle(leftCellStyle);
        }
        sheet.addMergedRegion(new CellRangeAddress(fromRowNum, fromRowNum, fromColNum, fromColNum + x));

        Row boardCodeRow = sheet.createRow(fromRowNum + 1);
        Cell boardCodeCell = boardCodeRow.createCell(fromColNum);
        boardCodeCell.setCellStyle(leftCellStyle);
        boardCodeCell.setCellValue(I18nHelper.getMessage("T_LIMS_RUN_BOARD.BOARDCODE").concat("：").concat(StringUtils.isBlank(runBean.getBoardCode()) ? "" : runBean.getBoardCode()));
        for (int i = fromColNum + 1; i <= x + fromColNum; i++) {
            Cell cell = boardCodeRow.createCell(i);
            cell.setCellStyle(leftCellStyle);
        }
        sheet.addMergedRegion(new CellRangeAddress(fromRowNum + 1, fromRowNum + 1, fromColNum, fromColNum + x));

        Row titleRow = sheet.createRow(fromRowNum + 2);
        titleRow.createCell(fromColNum).setCellStyle(centerCellStyle);
        for (int i = 1 + fromColNum; i <= x + fromColNum; i++) {
            Cell titleCell = titleRow.createCell(i);
            titleCell.setCellValue(i - fromColNum);
            titleCell.setCellStyle(centerCellStyle);
        }
        // x是列，y是行
        for (int i = 1 + fromRowNum + 2; i <= y + fromRowNum + 2; i++) {
            Row dataRow = sheet.createRow(i);
            Cell firstCell = dataRow.createCell(fromColNum);
            firstCell.setCellStyle(centerCellStyle);
            char c = (char) (i - 1 - fromRowNum - 2 + 65);
            firstCell.setCellValue(String.valueOf(c));
            for (int j = 1 + fromColNum; j <= x + fromColNum; j++) {
                Cell dataCell = dataRow.createCell(j);
                dataCell.setCellStyle(centerCellStyle);
                int finalI = i;
                int finalJ = j;
                runBoardHoleBeans.stream().filter(h -> h.getX().equals(finalJ - fromColNum) && h.getY().equals(finalI - fromRowNum - 2)).findFirst().ifPresent(h -> {
                    dataCell.setCellValue(h.getExt$Item("SAMPLECODE"));
                });
            }
        }
    }
}
